import React, { memo, useState, useEffect } from 'react'

import type { ReactNode } from 'react'
import { VIPWrapper } from './style'
import VIP from '@/assets/img/dis_vip_card.png'
import { Modal } from 'antd'
import Login from '@/views/login'
import { useAppDispatch, useAppSelector } from '@/store'
import { useRef } from 'react'
import {
  fetchLoginKeyAction,
  fetchLoginQRCodeAction,
  fetchLoginQRCodeStatusAction
} from '@/views/login/store/login'

interface IProps {
  children?: ReactNode
}

const VIPArea: React.FC<IProps> = () => {
  const [isModalOpen, setIsModalOpen] = useState(false)
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)
  const dispatch = useAppDispatch()
  const { unikey, loginQRCodeStatus } = useAppSelector((state) => ({
    unikey: state.login.unikey,
    loginQRCodeStatus: state.login.loginQRCodeStatus
  }))

  useEffect(() => {
    dispatch(fetchLoginKeyAction())
  }, [])
const showModal = () => {
    setIsModalOpen(true)
    dispatch(fetchLoginKeyAction()).then(() => {
      console.log(unikey, '打开后的unikey')
      if (unikey) {
        dispatch(fetchLoginQRCodeAction(unikey))
        if (timerRef.current) {
          clearInterval(timerRef.current)
          timerRef.current = null
        }
        timerRef.current = setInterval(() => {
          dispatch(fetchLoginQRCodeStatusAction(unikey))
        }, 3000)
      }
    })
  }

  const handleCancel = () => {
    setIsModalOpen(false)
    console.log('关闭弹窗')
    if (timerRef.current) {
      clearInterval(timerRef.current)
      timerRef.current = null
    }
  }

    useEffect(() => {
    if (!timerRef.current) return
    if (loginQRCodeStatus === 800) {
      clearInterval(timerRef.current)
      timerRef.current = null
    } else if (loginQRCodeStatus === 801) {
      console.log('带扫码')
    } else if (loginQRCodeStatus === 802) {
      console.log('待确认')

    } else if (loginQRCodeStatus === 803) {
      setIsModalOpen(false)
      clearInterval(timerRef.current)
      timerRef.current = null
      console.log('登录成功', loginQRCodeStatus)
    } else{
      clearInterval(timerRef.current)
      timerRef.current = null
    }
  }, [loginQRCodeStatus])

  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current)
        timerRef.current = null
      }
    }
  }, [])
  return (
    <VIPWrapper>
      <img className="img" src={VIP} alt="" />
      <p>登录网易云音乐，可以享受无限收藏的乐趣，并且无限同步到手机</p>
      <a className="sprite_02" onClick={showModal}>
        用户登录
      </a>
      <Modal
        title="登录"
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={isModalOpen}
        onCancel={handleCancel}
        mask={false}
        centered
        footer={null}
      >
        <Login />
      </Modal>
    </VIPWrapper>
  )
}

export default memo(VIPArea)
